package com.tuju.jetpackfirstdemo.ui.room_demo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.baize.fireeyekotlin.utils.log.L
import com.tuju.jetpackfirstdemo.R
import com.tuju.jetpackfirstdemo.data.room.Injection
import com.tuju.jetpackfirstdemo.data.room.User
import com.tuju.jetpackfirstdemo.data.room.UserDao
import com.tuju.jetpackfirstdemo.utils.showToast
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_room_demo.*

class RoomDemoActivity : AppCompatActivity() {

    private lateinit var viewModelFactory: RoomViewModelFactory
    private lateinit var viewModel: RoomViewModel

    private val disposable = CompositeDisposable()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room_demo)
        viewModelFactory = Injection.provideViewModelFactory(this)
        viewModel = ViewModelProviders.of(this@RoomDemoActivity, viewModelFactory).get(RoomViewModel::class.java)

        update_user_button.setOnClickListener {
            updateUserName()
        }
    }

    private fun updateUserName() {
        val targerName = et_modify_name.text.toString()
        disposable.add(viewModel.updateUserName(targerName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    showToast(msg = "修改成功")
                }, {
                    L.e(msg = "修改失败：${it.message}")
                }))
    }

    override fun onStart() {
        super.onStart()
        val dispos = viewModel.userName()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    tv_user_name.text = it
                }, {
                    L.e(msg = "修改失败：${it.message}")
                })
        disposable.add(dispos)
    }

    override fun onStop() {
        super.onStop()
        disposable.clear()
    }

    companion object {
        // using a hardcoded value for simplicity
        const val USER_ID = "1"
    }

}
